import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/store'
import _this from './main.js'
import axios from '@/utils/axios'
import { setCookie, getCookie } from '@/utils/cookie'
import { quickLogin } from 'api'

function postQuickLogin (query) {
  return new Promise(async (resolve, reject) => {
    try {
      const { ResultSet } = await axios.post(quickLogin, { code: query.code, state: query.state })
      await setCookie('CNPASS', ResultSet.userData.token, 15)
      resolve(ResultSet)
    } catch (err) {
      _this.message({ show: true, content: err.message || err.ResultSet.errors })
    }
  })
}

Vue.use(Router)

const _import = filePath => () => import('./views/' + filePath + '.vue')

const router = new Router({
  mode: 'history',
  base: '/pad',
  routes: [
    {
      path: '/',
      redirect: '/index'
    },
    // 首页
    {
      path: '/index',
      name: 'index',
      component: _import('index'),
      meta: { header: true }
    },
    // 列表
    {
      path: '/list',
      name: 'list',
      component: _import('list'),
      meta: { header: true }
    },
    // 详情
    {
      path: '/detail/:id',
      name: 'detail',
      component: _import('detail'),
      meta: { header: true }
    },
    {
      path: '/statistics',
      name: 'statistics',
      component: _import('statistics'),
      meta: { header: false }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.name === 'index' && to.query.appid === 'wwdfc157b24bebba67') {
    postQuickLogin(to.query).then(() => {
      store.dispatch('loadUserInfo', { next, to, redirect: '/index' })
    })
  } else {
    const userInfo = localStorage.getItem('USERINFO')
    if (userInfo) store.dispatch('changeUserInfo', JSON.parse(userInfo))
    next()
    // if (!store.getters.name) store.dispatch('loadUserInfo', { next, to })
    // else next() 
    // next()
  }
})

export default router
